package com.course.web.component.custom;

import com.course.web.biz.WebClassBiz;
import com.course.web.component.base.BaseEdit;
import com.course.web.component.base.BaseGrid;
import com.course.web.component.base.EditGrid;
import com.course.web.model.ClassMarkVM;
import com.course.web.view.StudentListView;
import com.vaadin.data.Binder;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.spring.annotation.ViewScope;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.renderers.DateRenderer;
import com.vaadin.ui.renderers.Renderer;

import java.text.SimpleDateFormat;

/**
 * Created by Justin on 2017/7/1.
 */
@SpringComponent
@ViewScope
public class ClassMarkGrid extends EditGrid<ClassMarkVM> {

    private final WebClassBiz classBiz;

    public ClassMarkGrid(WebClassBiz classBiz) {
        super(ClassMarkVM.class);
        this.classBiz = classBiz;
    }

    @Override
    protected void doInitMenu(Layout menu) {
        Button back = new Button("返回");
        menu.addComponent(back);
        back.addClickListener(event -> getUI().getNavigator().navigateTo(StudentListView.NAME));
    }

    @Override
    protected void doInitGrid(BaseGrid<ClassMarkVM> grid) {
        Renderer renderer = new DateRenderer(new SimpleDateFormat("MM-dd HH:mm"));
        grid.addColumn(ClassMarkVM::getTask, "课程名称");
        grid.addColumn(ClassMarkVM::getDate, "开始时间").setRenderer(renderer);
        grid.addColumn(ClassMarkVM::getTeacher, "上课老师");
        grid.addButton(this::updateShow, "翻译");
    }

    @Override
    protected void doInitEdit(BaseEdit<ClassMarkVM> edit) {
        FormLayout form = new FormLayout();
        TextArea suggest = new TextArea("Suggest");
        TextArea comment = new TextArea("Comment");
        TextArea sugCn = new TextArea("建议");
        TextArea comCn = new TextArea("留言");
        form.addComponent(suggest);
        form.addComponent(comment);
        form.addComponent(sugCn);
        form.addComponent(comCn);
        form.setMargin(false);
        suggest.setEnabled(false);
        comment.setEnabled(false);
        edit.initEdit(form);

        Binder<ClassMarkVM> binder = edit.binder();
        binder.forField(suggest).bind("suggest");
        binder.forField(comment).bind("comment");
        binder.forField(sugCn).bind("sugCn");
        binder.forField(comCn).bind("comCn");
    }

    @Override
    protected ClassMarkVM doUpdate(ClassMarkVM item) {
        return classBiz.updateMark(item);
    }

    public void enter(int studentId) {
        init(classBiz.findMarkByStudent(studentId));
    }
}
